package com.threeox.httplibrary.request;

import com.threeox.httplibrary.OkHttpUtils;
import com.threeox.httplibrary.callback.Callback;
import com.threeox.httplibrary.utils.Exceptions;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 *
 * @ClassName: PostFileRequest
 *
 * @Description: Todo(PostFile请求方式)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/21 11:25
 *
 * @version 1.0
 */
public class PostFileRequest extends OkHttpRequest {

    private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
    private File file;
    private MediaType mediaType;

    public PostFileRequest(String url, Object tag, Map<String, Object> params, Map<String, Object> headers, File file, MediaType mediaType, int id) {
        super(url, tag, params, headers,id);
        this.file = file;
        this.mediaType = mediaType;
        if (this.file == null) {
            Exceptions.illegalArgument("文件不能为空!");
        }
        if (this.mediaType == null) {
            this.mediaType = MEDIA_TYPE_STREAM;
        }
    }

    @Override
    protected RequestBody buildRequestBody() {
        return RequestBody.create(mediaType, file);
    }

    @Override
    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) {
        if (callback == null) {
            return requestBody;
        }
        CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
        {
            @Override
            public void onRequestProgress(final long bytesWritten, final long contentLength)
            {

                OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength, id, url);
                    }
                });

            }
        });
        return countingRequestBody;
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }



}
